<template>
  <div v-clickoutside="handleClose" class="selectInput">
    <div class="input-box">
      <e-input
        :placeholder="placeholder"
        :value="inputValue"
        @on-focus="handleInput"
        type="text"
        clearable
        readonly
        ref="myInput"
        :disabled="disabled"
      >
        <template #suffix>
          <i :class="['fa', {'fa-caret-down': !dropdownShow, 'fa-caret-up': dropdownShow}]"></i>
        </template>
      </e-input>
    </div>
    <div v-show="dropdownShow" class="input-dropdown" :style="dropdownWidth()">
      <div class="dropdown-title">
        <e-input placeholder="搜索" v-model="search">
          <template #prefix>
            <i class="fa fa-search"></i>
          </template>
        </e-input>
        <e-button type="text" style="margin-left: 8px;" @click="switchDepartment">
          <i class="fa fa-sitemap"></i>按部门
        </e-button>
      </div>
      <div class="dropdown-content">
        <div v-show="!showDepartment">
          <virtual-list :sourceList="peopleListFilter">
            <template #default="{item}">
              <div
                :class="['people-list',{'selected': users.includes(item.username) }]"
                @click="choose(item)"
              >
                <span class="avatar">{{item.avatar}}</span>
                <span class="name">
                  <p>{{item.realname}}</p>
                  <p>{{item.companyNameDis}}、{{item.orgNameDis}}</p>
                </span>
              </div>
            </template>
          </virtual-list>
        </div>
        <div v-show="showDepartment">
          <select-org-person
            @selectUsers="selectUsers"
            :companyName="companyName"
            :multiple="multiple"
            :selected="selected"
            :search="search"
          ></select-org-person>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import clickoutside from './utils/clickoutside';
import selectOrgPerson from './select-user/index.vue';
import virtualList from './virtual-list/index.vue';
export default {
  name: 'select-person',
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    // 父组件传递的输入框初始值
    username: {
      type: String,
      default: '', // '例如：1~2'
    },
    // 输入框的提示
    placeholder: {
      type: String,
      default: '请输入名字',
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  computed: {},
  data() {
    return {
      //  控制下拉列表显示
      dropdownShow: false,
      showDepartment: false,
      peopleList: [],
      selected: [],
      search: ''
    };
  },
  directives: {
    // 自定义指令用于处理点击组件区域之外的click事件
    clickoutside,
  },
  created() {
    this.initPeople();
  },
  computed: {
    // 获取搜索后的数据
    peopleListFilter(){
      if (this.search) {
        return this.peopleList.filter(i=>{
          return i.username.includes(this.search) || i.orgNameDis?.includes(this.search) || i.realname?.includes(this.search)
        })
      }else{
        return this.peopleList
      }
    },
    users() {
      return this.selected.map((i) => i.username);
    },
    inputValue() {
      return this.selected.map((i) => i.realname).join(',');
    },
  },
  watch: {
    username: {
      immediate: true,
      // deep: true,
      handler(val) {
        if (val) {
          this.$http
            .post(
              '/cafe.portal-service/frame_center/define/query/list/PortalCompanyUser_QT475-297',
              {
                queryOpBeans: [
                  {
                    key: 'username',
                    filedType: 2,
                    op: 0,
                    value: val,
                  },
                ],
              }
            )
            .then(({ data }) => {
              if (data.success) {
                if (data.object.resultList.length === 0) {
                  this.selected = val.split('~').map((i) => {
                    return {
                      username: i,
                      realname: i,
                    };
                  });
                  return;
                }
                this.selected = data.object.resultList.map((i) => {
                  return {
                    username: i.username,
                    realname: i.realName,
                  };
                });
              } else {
                this.selected = val.split('~').map((i) => {
                  return {
                    username: i,
                    realname: i,
                  };
                });
              }
            });
        }
      },
    },
  },
  components: {
    selectOrgPerson,
    virtualList,
  },
  methods: {
    initPeople() {
      this.$http
        .post(
          '/cafe.portal-service/frame_center/define/query/list/querySalesLeader'
        )
        .then(({ data }) => {
          this.peopleList = data.object.resultList.map((i) => {
            i.orgNameDis = this.$locale(JSON.parse(i.orgName));
            i.avatar = i.realname && i['realname'].substr(-1);
            i.companyNameDis = this.$locale(JSON.parse(i.companyName));
            return i;
          });
          this.companyName =
            this.peopleList[0] && this.peopleList[0].companyNameDis;
        });
    },
    switchDepartment() {
      this.showDepartment = !this.showDepartment;
    },
    choose(item) {
      if (this.multiple) {
        const index = this.selected.findIndex(
          (i) => i.username === item.username
        );
        if (index > -1) {
          this.selected.splice(index, 1);
        } else {
          this.selected.push(item);
        }
      } else {
        this.selected = [item];
      }
    },
    selectUsers(list) {
      this.selected = list;
    },
    getValues() {
      return this.selected;
    },
    dropdownWidth() {
      if (this.$refs.myInput) {
        let width = window.getComputedStyle(this.$refs.myInput.$el).width;
        return {
          width,
        };
      } else {
        return {};
      }
    },
    // 输入框输入处理函数
    handleInput: function () {
      this.dropdownShow = true;
    },
    // 下拉列表隐藏处理函数
    handleClose: function () {
      this.dropdownShow = false;
    },
  },
};
</script>

<style scoped lang='less'>
.selectInput {
  position: relative;
  .input-dropdown {
    z-index: 999;
    min-width: 200px;
    min-height: 50px;
    position: absolute;
    line-height: 1.5;
    top: 35px;
    left: 0;
    background-color: #fff;
    // border: 1px solid #cfcfcf;
    // padding: 10px;
    padding-bottom: 10px;
    box-shadow: 0 2px 10px 0 #cfcfcf;
    .dropdown-title {
      display: flex;
      align-items: start;
      justify-content: space-between;
      padding: 10px 10px 0;
    }
    .dropdown-content {
      margin-top: 10px;
      .selected {
        background-color: #f2f2f2;
      }
      .people-list {
        display: flex;
        align-items: center;
        padding: 5px 10px;
        &:hover {
          background-color: #f2f2f2;
        }
        .avatar {
          display: inline-block;
          // width: 10px;
          padding: 2px 5px;
          border-radius: 50%;
          color: white;
          background-color: #95a3b9;
        }
        .name {
          margin-left: 10px;
          p:nth-child(2) {
            color: #999999;
            font-size: 10px;
          }
        }
      }
      .org-lsit {
        justify-content: space-between;
      }
    }
  }
}
</style>
